package com.zx.chatclient.fx.controller;

import java.net.URL;
import java.util.ResourceBundle;

import com.zx.chatclient.dto.IMMessage;
import com.zx.chatclient.dto.IMUser;
import com.zx.chatclient.netty.Client;
import com.zx.chatclient.util.contants.ChatContants;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;

public class LoginController implements ControlledStage, Initializable {

	private StageController myController;

	@FXML
	private TextField userText;

	@FXML
	private PasswordField pwdText;

	@FXML
	private Button loginButton;
	
	@FXML
	private Label msgLabel;

	@Override
	public void initialize(URL location, ResourceBundle resources) {

	}

	@Override
	public void setStageController(StageController stageController) {
		this.myController = stageController;
	}

	public void login(ActionEvent event) {
		IMUser user = new IMUser(userText.getText().trim(), null, null);
		IMMessage message = new IMMessage("1", "1", user, ChatContants.MSGTYPE_LOGIN, null, "登录",pwdText.getText().trim(),null);
		Client.setUser(user);
		try {
			Client.start();
			for (int i = 0; i < 10; i++) {
				try {
					Thread.sleep(100L);
					Client.getClientHander().setStageController(myController);
					if (Client.getClientHander().sendMsg(message)) {
						break;
					}
				} catch (Exception e) {
//					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
